package com.golddaymicromall.activity.setting.personal.address;

import android.os.Bundle;
import android.text.InputType;
import android.view.View;


import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;

import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.golddaymicromall.activity.R;
import com.golddaymicromall.application.MyApplication;
import com.golddaymicromall.base.BaseActivity;
import com.golddaymicromall.bean.AreaInfo;
import com.golddaymicromall.bean.CityInfo;
import com.golddaymicromall.bean.CountryInfo;
import com.golddaymicromall.bean.ProvinceInfo;
import com.golddaymicromall.util.RopUtils;
import com.golddaymicromall.util.SPUtils;
import com.golddaymicromall.util.ServerConfig;
import com.google.common.collect.Maps;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx.RxAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import rx.android.schedulers.AndroidSchedulers;

public class NewAddShouHuoActivity extends BaseActivity implements View.OnClickListener {

    //工具类

    private Spinner mDizhiCountry;
    private Spinner mDizhiProvince;
    private Spinner mDizhiCity;
    private Spinner mDizhiArea;

    private List<String> listCountry = null;
    private List<ProvinceInfo> provinceInfo = null;
    private List<CountryInfo> countryInfo = null;
    private List<CityInfo> cityInfo = null;
    private List<AreaInfo> areaInfo = null;

    private String countryId;
    private String provinceId;
    private String cityId;
    private String areaId;

    private Button mDizhibtn;
    private CheckBox mDizhicb;

    private EditText mDizhinumber;
    private EditText mDizhidetil;
    private EditText mDizhiname;
    private EditText mDizhitelephone;
    private EditText mDizhistreet;
    private LinearLayout mShouhuo_back;

    private String mDizhinumbers;
    private String mDizhidetils;
    private String mDizhinames;
    private String mDizhitelephones;
    private String mDizhistreets;
    private String flag = "1";
    private String Customerno;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_add_shou_huo);
        attemptGetCountryTask();
        attemptGetProvinceTask();
        initView();
        Customerno = SPUtils.get(getApplicationContext(), "Customerno", "").toString();
    }

    public void initView() {
        mDizhibtn = (Button) findViewById(R.id.Dizhibtn);
        mDizhibtn.setOnClickListener(this);
        mDizhiCountry = (Spinner) findViewById(R.id.DizhiCountry);
        mDizhiProvince = (Spinner) findViewById(R.id.DizhiProvince);
        mDizhiCity = (Spinner) findViewById(R.id.DizhiCity);
        mDizhiArea = (Spinner) findViewById(R.id.DizhiArea);

        mDizhistreet = (EditText) findViewById(R.id.Dizhistreet);
        mDizhiname = (EditText) findViewById(R.id.Dizhiname);
        mDizhitelephone = (EditText) findViewById(R.id.Dizhitelephone);

        mDizhitelephone.setInputType(InputType.TYPE_CLASS_PHONE);//电话

        mDizhicb = (CheckBox) findViewById(R.id.Dizhicb);
        mShouhuo_back = (LinearLayout) findViewById(R.id.shouhuo_back);
        mShouhuo_back.setOnClickListener(this);

    }

    private void attemptGetCountryTask() {
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.address.getcountry");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);
        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    if (!"".equals(s)) {
                        if (s.contains("errorToken") || "0".equals(s)) {
                            Toast.makeText(getApplicationContext(), "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(s)) {
                            Toast.makeText(getApplicationContext(), "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            countryInfo = JSON.parseArray(s, CountryInfo.class);
                            listCountry = new ArrayList<String>();
                            for (int i = 0; i < countryInfo.size(); i++) {
                                listCountry.add(countryInfo.get(i).getName());
                            }
                            // adpater对象
                            final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(NewAddShouHuoActivity.this, android.R.layout.simple_spinner_dropdown_item, listCountry);
                            mDizhiCountry.setAdapter(arrayAdapter);
                            mDizhiCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                @Override
                                public void onItemSelected(AdapterView<?> parent, View view,
                                                           int position, long id) {
                                    Spinner spinner = (Spinner) parent;
                                    for (int i = 0; i < countryInfo.size(); i++) {
                                        if (spinner.getItemAtPosition(position).toString().equals(countryInfo.get(i).getName())) {
                                            countryId = countryInfo.get(i).getId();
                                        }
                                    }
                                }

                                @Override
                                public void onNothingSelected(AdapterView<?> parent) {
                                    Toast.makeText(getApplicationContext(), "没有改变的处理",
                                            Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "没有请求到数据,请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                }, throwable -> {
                    showError();
                    throwable.printStackTrace();
                });

    }
    private void attemptGetProvinceTask() {
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.address.getprovinces");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);
        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    if (!"".equals(s)) {
                        if (s.contains("errorToken") || "0".equals(s)) {
                            Toast.makeText(getApplicationContext(), "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(s)) {
                            Toast.makeText(getApplicationContext(), "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            provinceInfo = JSON.parseArray(s, ProvinceInfo.class);
                            final List<String> listProvince = new ArrayList<String>();
                            for (int i = 0; i < provinceInfo.size(); i++) {
                                listProvince.add(provinceInfo.get(i).getName());
                            }
                            // adpater对象
                            final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(NewAddShouHuoActivity.this, android.R.layout.simple_spinner_dropdown_item, listProvince);

                            mDizhiProvince.setAdapter(arrayAdapter);
                            mDizhiProvince.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                @Override
                                public void onItemSelected(AdapterView<?> parent, View view,
                                                           int position, long id) {
                                    Spinner spinner = (Spinner) parent;
                                    for (int i = 0; i < provinceInfo.size(); i++) {
                                        if (spinner.getItemAtPosition(position).toString().equals(provinceInfo.get(i).getName())) {
                                            provinceId = provinceInfo.get(i).getId();
                                            attemptGetCityTask(provinceId);
                                        }
                                    }
                                }

                                @Override
                                public void onNothingSelected(AdapterView<?> parent) {
                                    Toast.makeText(getApplicationContext(), "没有改变的处理",
                                            Toast.LENGTH_LONG).show();
                                }
                            });
                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "没有请求到数据,请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                }, throwable -> {
                    showError();
                    throwable.printStackTrace();
                });
    }
    private void attemptGetCityTask(String provinceId) {
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.address.getcity");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("province", provinceId);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);
        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    if (!"".equals(s)) {
                        if (s.contains("errorToken") || "0".equals(s)) {
                            Toast.makeText(getApplicationContext(), "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(s)) {
                            Toast.makeText(getApplicationContext(), "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            cityInfo = JSON.parseArray(s, CityInfo.class);
                            final List<String> listCity = new ArrayList<String>();
                            for (int i = 0; i < cityInfo.size(); i++) {
                                listCity.add(cityInfo.get(i).getName());
                            }
                            // adpater对象
                            final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(NewAddShouHuoActivity.this, android.R.layout.simple_spinner_dropdown_item, listCity);
                            mDizhiCity.setAdapter(arrayAdapter);
                            mDizhiCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                @Override
                                public void onItemSelected(AdapterView<?> parent, View view,
                                                           int position, long id) {
                                    Spinner spinner = (Spinner) parent;
                                    for (int i = 0; i < cityInfo.size(); i++) {
                                        if (spinner.getItemAtPosition(position).toString().equals(cityInfo.get(i).getName())) {
                                            cityId = cityInfo.get(i).getId();
                                            attemptGetAreaTask(cityId);
                                        }
                                    }
                                }

                                @Override
                                public void onNothingSelected(AdapterView<?> parent) {
                                    Toast.makeText(getApplicationContext(), "没有改变的处理",
                                            Toast.LENGTH_LONG).show();
                                }
                            });


                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "没有请求到数据,请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                }, throwable -> {
                    showError();
                    throwable.printStackTrace();
                });


    }
    private void attemptGetAreaTask(String cityId) {
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.address.getdistrict");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("city", cityId);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);
        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    if (!"".equals(s)) {
                        if (s.contains("errorToken") || "0".equals(s)) {
                            Toast.makeText(getApplicationContext(), "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(s)) {
                            Toast.makeText(getApplicationContext(), "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            areaInfo = JSON.parseArray(s, AreaInfo.class);
                            final List<String> listArea = new ArrayList<String>();
                            for (int i = 0; i < areaInfo.size(); i++) {
                                listArea.add(areaInfo.get(i).getName());
                            }
                            // adpater对象
                            final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(NewAddShouHuoActivity.this, android.R.layout.simple_spinner_dropdown_item, listArea);
                            mDizhiArea.setAdapter(arrayAdapter);
                            mDizhiArea.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                @Override
                                public void onItemSelected(AdapterView<?> parent, View view,
                                                           int position, long id) {
                                    Spinner spinner = (Spinner) parent;
                                    for (int i = 0; i < areaInfo.size(); i++) {
                                        if (spinner.getItemAtPosition(position).toString().equals(areaInfo.get(i).getName())) {
                                            areaId = areaInfo.get(i).getId();
                                        }
                                    }
                                }

                                @Override
                                public void onNothingSelected(AdapterView<?> parent) {
                                    Toast.makeText(getApplicationContext(), "没有改变的处理",
                                            Toast.LENGTH_LONG).show();
                                }
                            });

                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "没有请求到数据,请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                }, throwable -> {
                    showError();
                    throwable.printStackTrace();
                });
    }



    private void attemptAddNewAdress(String logId, String mDizhinames, String mDizhitelephones, String mDizhistreet, String countryId, String provinceId, String cityId, String areaId, String flag) {
        Map<String, String> form = Maps.newHashMap();
        form.put("method", "rop.address.add");
        form.put("appKey", "00001");
        form.put("v", "1.0");
        form.put("format", "json");
        form.put("customerId", logId);
        form.put("country", countryId);
        form.put("province", provinceId);
        form.put("city", cityId);
        form.put("area", areaId);
        form.put("street", mDizhistreet);
        form.put("phone", mDizhitelephones);
        form.put("address_default", flag);
        form.put("receivername", mDizhinames);
        String sing = RopUtils.signString(form, "qwertyuiop");
        form.put("sign", sing);
        OkGo.post(new ServerConfig().SERVER)
                .params(form)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    if (!"".equals(s)) {
                        if (s.contains("errorToken") || "0".equals(s)) {
                            Toast.makeText(getApplicationContext(), "访问服务器失败,请稍后重试", Toast.LENGTH_SHORT).show();
                        } else if ("null".equals(s)) {
                            Toast.makeText(getApplicationContext(), "暂无数据", Toast.LENGTH_SHORT).show();
                        } else {
                            if (Integer.parseInt(s) == -1) {
                                Toast.makeText(NewAddShouHuoActivity.this, "信息不完整，请添加", Toast.LENGTH_SHORT).show();
                            } else if (Integer.parseInt(s) == 0) {
                                Toast.makeText(NewAddShouHuoActivity.this, "添加失败", Toast.LENGTH_SHORT).show();
                            } else if (Integer.parseInt(s) == 1) {
                                Toast.makeText(NewAddShouHuoActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                                finish();
                                MyApplication.getInstance().attemptRiZhi(Customerno, "地址添加");
                            }
                        }
                    } else {
                        Toast.makeText(getApplicationContext(), "没有请求到数据,请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                }, throwable -> {
                    showError();
                    throwable.printStackTrace();
                });
    }

    private void attemptAddNewAddressbefore() {
        if (mDizhicb.isChecked()) {
            flag = "1";
        } else {
            flag = "0";
        }

        String logid = SPUtils.get(getApplicationContext(), "Id", "").toString();
        mDizhistreets = mDizhistreet.getText().toString().trim();
        mDizhinames = mDizhiname.getText().toString().trim();
        mDizhitelephones = mDizhitelephone.getText().toString().trim();
        if (mDizhitelephones.length() != 11) {
            Toast.makeText(this, "手机号必须为11位", Toast.LENGTH_SHORT).show();
            return;
        }
        if ("".equals(mDizhitelephones)) {
            Toast.makeText(this, "联系电话不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!isphone(mDizhitelephones)) {
            Toast.makeText(this, "电话格式不正确", Toast.LENGTH_SHORT).show();
            return;
        }
        if ("".equals(mDizhistreets)) {
            Toast.makeText(this, "街道不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (isSpecial(mDizhistreets)) {
            Toast.makeText(this, "不能输入特殊字符", Toast.LENGTH_SHORT).show();
            return;
        }


        if ("".equals(mDizhinames)) {
            Toast.makeText(this, "详细地址名称不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (isSpecial(mDizhinames)) {
            Toast.makeText(this, "不能输入特殊字符", Toast.LENGTH_SHORT).show();
            return;
        }
        attemptAddNewAdress(logid, mDizhinames, mDizhitelephones, mDizhistreets, countryId, provinceId, cityId, areaId, flag);

    }

    public boolean isSpecial(String bz) {
        String regEx = "[`~!@#$%^&*()+=|{}':;'\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(bz);
        return m.find();
    }

    public boolean isNumber(String Num) {
        Pattern p = Pattern
                .compile("^[0-9]*$");
        Matcher m = p.matcher(Num);
        return m.matches();
    }

    public boolean isphone(String Num) {
        Pattern p = Pattern
                .compile("^1[3|4|5|7|8][0-9]\\d{8}$");
        Matcher m = p.matcher(Num);
        return m.matches();
    }

    public boolean ispostnum(String Num) {
        Pattern p = Pattern
                .compile("[1-9]\\\\d{5}(?!\\d)");
        Matcher m = p.matcher(Num);
        return m.matches();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.Dizhibtn:
                attemptAddNewAddressbefore();
                break;
            case R.id.shouhuo_back:
                finish();
                break;
        }
    }
}
